//
//  TPServersViewController.m
//  CloudAtCostPanel
//
//  Created by leonardo on 2017/1/26.
//  Copyright © 2017年 tanpengsccd. All rights reserved.
//

#import "TPServersViewController.h"
#import "TPServersTableViewCell.h"

#import "TPNetModel_Listservers.h"
#import "TPNetModel_RunMode.h"
#import "TPNetModel_RenameServer.h"
#import "TPNetModel_ModifyReverseDNS.h"
#import "TPNetModel_PowerOperations.h"
#import "TPNetModel_Delete.h"

#import <MJRefresh.h>
#import "TPBaseTableViewCell.h"
#import <LocalAuthentication/LocalAuthentication.h>
static NSString * const CELLID = @"cell";
@interface TPServersViewController ()<UITableViewDataSource ,UITableViewDelegate,TPBaseTableViewCellDelegate,UIScrollViewDelegate,UIGestureRecognizerDelegate>
PRO_S TPNetModel_Listservers_res * model_servers;
PRO_S UITableView * tableView_server;

@end

@implementation TPServersViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Servers";
    
    
    // Do any additional setup after loading the view.
    _tableView_server = [UITableView new];
    _tableView_server.separatorStyle = UITableViewCellSeparatorStyleNone;//移除分界线
//    [_tableView_server registerClass:[TPServersTableViewCell class] forCellReuseIdentifier:CELLID];
//    [_tableView_server registerClass:[TPBaseTableViewCell class] forCellReuseIdentifier:CELLID];
    _tableView_server.dataSource  = self;
    _tableView_server.delegate = self;
    _tableView_server.rowHeight = UITableViewAutomaticDimension;
    [_tableView_server setEstimatedRowHeight: 50];
    _tableView_server.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;//拖动时隐藏keyboard
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getListServersWithSender:)];
    _tableView_server.mj_header = header;
    
    
    [self.view addSubview:_tableView_server];
    
    self.navigationItem.leftBarButtonItem = self.editButtonItem;
    
    
    
    [self getListServersWithSender:self.view];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [_tableView_server mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.mas_equalTo(_tableView_server.superview);
    }];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - tableview
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    TPServersTableViewCell * cell = [_tableView_server dequeueReusableCellWithIdentifier:CELLID forIndexPath:indexPath];
//    [cell configWithModel:_model_servers.data[indexPath.row]];
    
    TPServersTableViewCell * cell = [_tableView_server dequeueReusableCellWithIdentifier:CELLID];
    if (!cell) {
        cell = [[TPServersTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CELLID rightBtns:[[TPCellUtilityBtns alloc] initWithTitles:@[@"Power off",@"Reboot",@"Delete"] Colors:@[COLOUR_YELLOW,COLOUR_GREEN,COLOUR_RED] width:80] leftBtns:[[TPCellUtilityBtns alloc] initWithTitles:@[@"Run\nmode",@"Rename",@"Hostname"] Colors:@[COLOUR_YELLOW,COLOUR_GREEN,COLOUR_RED] width:90]];//
    }
    [(UILabel *)cell.rightUtilityBtnsContainer.subviews[0].subviews[0] setText:[_model_servers.data[indexPath.row].status.lowercaseString containsString:@"on"]?@"Power off":@"Power on" ];
    
    [cell configWithModel:_model_servers.data[indexPath.row]];
    cell.delegate = self;
    
    return cell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _model_servers.data.count;
//    return 1;
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}
-(void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath{
    [self setEditing:YES animated:YES];
}
-(void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath{
    [self setEditing:NO animated:YES];
}
//-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    return  1;
//}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    
    DDLogWarn(@"%s , %@ ***** %@",__func__,gestureRecognizer,otherGestureRecognizer);
    return NO;
}
#pragma mark - cell deleagte
- (void)cell:(TPBaseTableViewCell *)cell indexPath:(NSIndexPath *)indexPath tapUtilityBtnsSide:(UtilityBtnsSide)side btnIndex:(NSUInteger)index{
    DDLogDebug(@"tap %@%lui",side == UtilityBtnsSide_right?@"right":@"left",(unsigned long)index);
    if (side == UtilityBtnsSide_Left) {
        switch (index) {//@"Run\nmode",@"Rename",@"Hostname"
            case 0:
            {
                NSString * mode_now = _model_servers.data[indexPath.row].mode;
                NSString * mode_will = [_model_servers.data[indexPath.row].mode.lowercaseString isEqualToString:@"safe"]?@"normal":@"safe";//原是Safe Normal
                //弹出提示HUD
                TPAlertView * alertChangeRunMode = [[TPAlertView alloc]initOkCancelWithTitle:[NSString stringWithFormat:@"Run mode is %@\nChange Run mode to %@?",mode_now,mode_will] subtitle:@"Safe automatically turns off the server after 7 days of idle usage, Normal keeps it on indefinitely."];
                
                [alertChangeRunMode setAlertViewTapBtnOkBlock:^(id objec) {
                
                    TPNetModel_RunMode_req * req = [[TPNetModel_RunMode_req alloc]init];
                    req.sid = _model_servers.data[indexPath.row].sid;
                    req.mode = mode_will;
                    
                    //弹出请求菊花HUD
                    [self showHUDWithReqModel:req progress:nil successGetModel:^(TPBaseNetModel_res * _Nullable resModel) {
                        //弹出操作成功与否HUD
                        [self showHudTips:@"Operation succeed！"];
                        [cell updateCellState:TPBaseTableViewCellState_Normal OffSetAnimated:YES];
                        _model_servers.data[indexPath.row].mode = mode_will;
                        [_tableView_server reloadData];
                    } failureGetModel:^(TPBaseNetModel_res * _Nullable resModel) {
                        [self showHudTipsWithResModel_error:resModel];
                    }];

                }];
                
                [[TPAlertViewController defaultCautionViewController] showAlertView:alertChangeRunMode animated:YES];
            }
                break;
            case 1:
            {
                NSString * label = _model_servers.data[indexPath.row].label;
                TPAlertView * alert = [[TPAlertView alloc]initTextFieldWithTitle:@"Enter a new label" subtitle:nil text:label placeholder:@"Enter a new label"];
                [alert setAlertViewTapBtnOkBlock:^(id objec) {
                    if ([objec isKindOfClass:[NSString class]]) {
                        TPNetModel_RenameServer_req * req = [[TPNetModel_RenameServer_req alloc]init];
                        req.sid = _model_servers.data[indexPath.row].sid;
                        req.name = objec;
                        [self showHUDWithReqModel:req progress:nil successGetModel:^(TPBaseNetModel_res * _Nullable resModel) {
                            [self showHudTips:@"Operation succeed！"];
                            [cell updateCellState:TPBaseTableViewCellState_Normal OffSetAnimated:YES];
                            _model_servers.data[indexPath.row].label = objec;
                            [_tableView_server reloadData];
                        } failureGetModel:^(TPBaseNetModel_res * _Nullable resModel) {
                            [self showHudTipsWithResModel_error:resModel];
                        }];
                    }
                }];
                [[TPAlertViewController defaultCautionViewController]showAlertView:alert animated:YES];
            }
                break;
            case 2:
            {
                NSString * rdns = _model_servers.data[indexPath.row].rdns;
                TPAlertView * alert = [[TPAlertView alloc]initTextFieldWithTitle:@"Modify the reverse DNS & hostname of the VPS" subtitle:nil text:rdns placeholder:@"Enter a new reverse DNS"];
                [alert setAlertViewTapBtnOkBlock:^(id objec) {
                    if ([objec isKindOfClass:[NSString class]]) {
                        TPNetModel_ModifyReverseDNS_req * req = [[TPNetModel_ModifyReverseDNS_req alloc]init];
                        req.sid = _model_servers.data[indexPath.row].sid;
                        req.hostname = [objec length]?objec : _model_servers.data[indexPath.row].rdnsdefault;
                        [self showHUDWithReqModel:req progress:nil successGetModel:^(TPBaseNetModel_res * _Nullable resModel) {
                            [self showHudTips:@"Operation succeed！"];
                            [cell updateCellState:TPBaseTableViewCellState_Normal OffSetAnimated:YES];
                            _model_servers.data[indexPath.row].hostname = objec;
                            [_tableView_server reloadData];
                        } failureGetModel:^(TPBaseNetModel_res * _Nullable resModel) {
                            [self showHudTipsWithResModel_error:resModel];
                        }];
                    }
                }];
                [[TPAlertViewController defaultCautionViewController]showAlertView:alert animated:YES];
            }
                break;
                
            default:
                break;
        }
    }else{
        switch (index) {//@"Power off",@"Reboot",@"Delete"
            case 0://power on/off
            case 1:// reboot
            {
                NSString * status_now = _model_servers.data[indexPath.row].status ;//Power On;Power Off
                NSString * action_will = index?@"Reboot":[status_now.lowercaseString containsString:@"on"]?@"PowerOff":@"PowerOn";
                 //弹出提示HUD
                TPAlertView * alert = [[TPAlertView alloc]initOkCancelWithTitle:[NSString stringWithFormat:@"%@ this server?",action_will] subtitle:nil];
                
                [alert setAlertViewTapBtnOkBlock:^(id objec) {
                    
                    TPNetModel_PowerOperations_req * req = [[TPNetModel_PowerOperations_req alloc]init];
                    req.sid = _model_servers.data[indexPath.row].sid;
                    req.action = [action_will.lowercaseString containsString:@"power"]? action_will.lowercaseString : @"reset";//poweron;poweroff;reset
                    
                    //弹出请求菊花HUD
                    [self showHUDWithReqModel:req progress:nil successGetModel:^(TPBaseNetModel_res * _Nullable resModel) {
                        //弹出操作成功与否HUD
                        [self showHudTips:@"Operation succeed!"];
                        [cell updateCellState:TPBaseTableViewCellState_Normal OffSetAnimated:YES];
                        _model_servers.data[indexPath.row].status = action_will;
                        [_tableView_server reloadData];
                    } failureGetModel:^(TPBaseNetModel_res * _Nullable resModel) {
                        [self showHudTipsWithResModel_error:resModel];
                    }];
                    
                }];
                
                [[TPAlertViewController defaultCautionViewController] showAlertView:alert animated:YES];
            }
                break;
            case 2:
            {
                //弹出提示HUD
                TPAlertView * alert = [[TPAlertView alloc]initOkCancelWithTitle:[NSString stringWithFormat:@"%@ this server?",@"Delete"] subtitle:nil];
                
                [alert setAlertViewTapBtnOkBlock:^(id objec) {
                    
                    TPNetModel_Delete_req * req = [[TPNetModel_Delete_req alloc]init];
                    req.sid = _model_servers.data[indexPath.row].sid;
                    
                    
                    //弹出请求菊花HUD
                    [self showHUDWithReqModel:req progress:nil successGetModel:^(TPBaseNetModel_res * _Nullable resModel) {
                        //弹出操作成功与否HUD
                        [self showHudTips:@"Operation succeed!"];
                        [cell updateCellState:TPBaseTableViewCellState_Normal OffSetAnimated:YES];
                        [_model_servers.data removeObjectAtIndex:indexPath.row];
                        [_tableView_server reloadData];
                    } failureGetModel:^(TPBaseNetModel_res * _Nullable resModel) {
                        [self showHudTipsWithResModel_error:resModel];
                    }];
                    
                }];
                
                [[TPAlertViewController defaultCautionViewController] showAlertView:alert animated:YES];
            }
                break;
                
            default:
                break;
        }
    }
}

-(void)cell:(TPBaseTableViewCell *)cell indexPath:(NSIndexPath *)indexPath ChangeToState:(TPBaseTableViewCellState)state{
    
}
#pragma mark - private

- (void)getListServersWithSender:(id)sender{
    TPAlertView * hud;
    NSURLSessionDataTask * task;
    if ([sender isEqual:self.view]) {
        hud = [TPAlertView sharedHUDView_Loading];
        [hud setAlertViewTapBtnCancelBlock:^(id objec) {
            
            [task cancel];
        }];
        [[TPAlertViewController defaultHUDViewController ]showAlertView:hud animated:YES];
    }
    task = [[TPNetworkingManager manager] TP_Cac_requestWithReqModel:[TPNetModel_Listservers_req new] progress:nil successGetModel:^(TPBaseNetModel_res * _Nullable resModel) {
        NSMutableArray * reverseArr = [[[(TPNetModel_Listservers_res *)resModel data] reverseObjectEnumerator] allObjects].mutableCopy;
        
        _model_servers = (TPNetModel_Listservers_res *)resModel;
        _model_servers.data = reverseArr;
        [_tableView_server reloadData];
        [_tableView_server.mj_header endRefreshing];
        [hud dismissAnimated:YES];
    } failureGetModel:^(TPBaseNetModel_res * _Nullable resModel) {
        
        [_tableView_server.mj_header endRefreshing];
        if (hud) {
            [hud dismissAnimated:YES];
            [self showHudTipsWithResModel_error:resModel];
            
        }else{
            [self showHudTipsWithResModel_error:resModel];
        }
        
    }];

}





/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
